<script setup lang="ts">
import { computed, onMounted, ref, onBeforeUnmount, watch, watchEffect } from 'vue'
import { useTitle } from '@/hooks/useTitle'
import { projectsData } from '@/mock/mockdata'
import type { IProject } from '@/mock/mockdata'
import ProjectCard from '@/components/ProjectCard.vue'
import { useRoute } from 'vue-router'

const route = useRoute()
useTitle('Home')

const visibleProjects = ref<IProject[]>([])
const loading = ref(false)
const noMoreData = ref(false)
const pageSize = 6 // 每次加载的项目数量
let currentPage = 0

const searchQuery = ref<string>('') // 用于存储搜索词
const categoryQuery = ref<string>('') // 用于存储分类词

watchEffect(() => {
  searchQuery.value = (route.query.keyword as string) || ''
  categoryQuery.value = (route.query.category as string) || ''
})

// 模拟从“后端”获取数据
const loadMoreProjects = () => {
  if (loading.value || noMoreData.value) return

  loading.value = true
  const nextPage = currentPage + 1

  setTimeout(() => {
    const start = currentPage * pageSize
    const end = start + pageSize
    const newProjects = projectsData.slice(start, end)

    if (newProjects.length > 0) {
      visibleProjects.value.push(...newProjects)
      currentPage = nextPage
    } else {
      noMoreData.value = true
    }

    loading.value = false
  }, 500)
}

// 监听页面滚动事件，实现无限滚动
const observer = new IntersectionObserver(
  (entries) => {
    if (entries[0].isIntersecting) {
      loadMoreProjects()
    }
  },
  {
    root: null,
    threshold: 0.1
  }
)

onMounted(() => {
  loadMoreProjects() // 初次加载数据
  const scrollAnchor = document.querySelector('.scroll-anchor')
  if (scrollAnchor) {
    observer.observe(scrollAnchor)
  }
})

onBeforeUnmount(() => {
  observer.disconnect()
})

const filteredProjects = computed(() => {
  let projects = visibleProjects.value

  if (categoryQuery.value) {
    projects = projects.filter(
      (project) => project.category.toLowerCase() === categoryQuery.value.toLowerCase()
    )
  }

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    projects = projects.filter((project) => {
      return (
        project.title.toLowerCase().includes(query) ||
        project.description.toLowerCase().includes(query) ||
        project.tags.some((tag) => tag.toLowerCase().includes(query)) ||
        project.techStack.some((tech) => tech.toLowerCase().includes(query))
      )
    })
  }

  return projects
})

const sortedProjects = computed(() => {
  return filteredProjects.value.sort(
    (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
  )
})
</script>

<template>
  <el-container class="home-container">
    <el-row :gutter="20" class="project-row">
      <!-- 数据加载完成但没有结果 -->
      <template v-if="sortedProjects.length === 0 && !loading">
        <div class="empty-container">
          <el-empty description="No projects found." />
        </div>
      </template>

      <!-- 数据加载完成并有结果 -->
      <template v-else>
        <el-col :span="8" v-for="project in sortedProjects" :key="project.id" class="project-col">
          <ProjectCard :project="project" />
        </el-col>
      </template>
    </el-row>
    <!-- <div v-loading="loading" class="loading" element-loading-text="Loading..."></div> -->
    <!-- 加载中 -->
    <template v-if="loading">
      <div v-loading="loading" class="loading" element-loading-text="Loading..."></div>
    </template>
    <div v-if="noMoreData" class="no-more-data">
      <p>已经到底部了</p>
    </div>
    <div class="scroll-anchor"></div>
  </el-container>
</template>

<style scoped lang="scss">
.home-container {
  /* 确保容器占据最小的100%视口高度，避免内部滚动 */
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  overflow: visible; /* 确保没有滚动条 */
  display: flex;
  flex-direction: column;
  .project-row {
    .empty-container {
      width: 100%;
    }
  }
}

.project-col {
  padding: 10px;
}

.loading {
  text-align: center;
  margin: 20px 0;
}

.no-more-data {
  text-align: center;
  color: #999;
  margin: 20px 0;
}
</style>
